<template>
	<div>
		<div class="addAgent-content">
			<div class="form-header">
				<h4>{{ $t('funds.capital_adjustment.form_title3') }}</h4>
				<span>
					<code style="color:#FF3B30;">*</code>
					{{ $t('common.add_dialog_tips') }}
				</span>
			</div>
			<el-divider></el-divider>
			<el-form
				ref="formRef"
				class="form-box"
				:model="queryData"
				:rules="rules"
				label-width="auto"
			>
				<el-form-item
					:label="`${$t('common.choose_merchant')}:`"
					prop="merchantId"
				>
					<merchant-select
						v-model="queryData.merchantId"
						:placeholder="$t('common.please_choose')"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('funds.capital_adjustment.activity_title')}:`"
					prop="activityTitle"
				>
					<el-select
						v-model="queryData.activityTitle"
						filterable
						clearable
						size="medium"
						:placeholder="
							$t('funds.capital_adjustment.activity_title')
						"
					>
						<el-option
							v-for="item in activityTitleList"
							:key="item.id"
							:label="item.activityTitle"
							:value="item.activityTitle"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('funds.capital_adjustment.operation_type')}:`"
					prop="operationType"
				>
					<el-button
						:type="queryData.operationType === 1 ? 'primary' : ''"
						@click="handleOperation(1)"
					>
						{{ $t('funds.capital_adjustment.operation_type_1') }}
					</el-button>
					<el-button
						:type="queryData.operationType === 2 ? 'primary' : ''"
						@click="handleOperation(2)"
					>
						{{ $t('funds.capital_adjustment.operation_type_2') }}
					</el-button>
				</el-form-item>
				<el-form-item
					prop="location"
					:label="`${$t('funds.capital_adjustment.send_location')}:`"
				>
					<el-radio
						v-model="queryData.location"
						:label="1"
						@change="queryData.location = 1"
					>
						{{ $t('funds.capital_adjustment.wallet_center') }}
					</el-radio>
					<!-- <el-radio
						v-model="queryData.location"
						:label="2"
						@change="queryData.location = 2"
					>
						红利中心
					</el-radio> -->
				</el-form-item>
				<el-form-item
					v-if="queryData.operationType === 1"
					prop="userName"
					:label="`${$t('funds.user_name')}:`"
				>
					<el-input
						v-model="queryData.userName"
						size="medium"
						:placeholder="
							$t('funds.capital_adjustment.user_name_placeholder')
						"
						maxlength="11"
						clearable
						@blur="searchUserName"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="queryData.operationType === 1"
					key="amount"
					:label="`${$t('funds.bonus_amount')}:`"
					prop="bounsAmount"
				>
					<el-input-number
						v-model="queryData.bounsAmount"
						:placeholder="
							$t(
								'funds.capital_adjustment.bouns_amount_placeholder'
							)
						"
						:controls="false"
						:min="0.01"
						:max="999999999999.99"
						:precision="2"
						style="width:100%"
					></el-input-number>
					<span style="position: absolute;left: 4px;color: #909399;">
						{{ handleCurrency(currency, true) }}
					</span>
				</el-form-item>
				<el-form-item
					v-if="queryData.operationType === 2"
					prop="fileUrl"
					:label="`${$t('funds.capital_adjustment.file_url')}:`"
				>
					<el-button plain @click="downloadExcel">
						<svg-icon icon-class="down" class="up-icon" />
						{{ $t('funds.capital_adjustment.download_template') }}
					</el-button>
					<el-button plain @click="handleExport">
						<svg-icon icon-class="up" class="down-icon" />
						{{ $t('funds.capital_adjustment.batch_import') }}
					</el-button>
				</el-form-item>
				<el-form-item
					key="billMultiple"
					:label="`${$t('funds.capital_adjustment.bill_multiple')}:`"
					prop="billMultiple"
				>
					<el-input-number
						v-model="queryData.billMultiple"
						:placeholder="
							$t(
								'funds.capital_adjustment.bill_multiple_placeholder'
							)
						"
						:controls="false"
						:min="0"
						:max="99"
						:precision="0"
						style="width:100%;"
					></el-input-number>
					<span class="number-box">
						{{ $t('funds.capital_adjustment.multiple') }}
					</span>
				</el-form-item>
				<el-form-item
					v-if="queryData.location === 1"
					prop="notification"
					:label="`${$t('funds.capital_adjustment.notification')}:`"
				>
					<template>
						<el-radio v-model="queryData.notification" :label="0">
							{{ $t('common.no') }}
						</el-radio>
						<el-radio v-model="queryData.notification" :label="1">
							{{ $t('common.yes') }}
						</el-radio>
					</template>
				</el-form-item>
				<el-form-item
					key="remark"
					:label="`${$t('common.remark')}:`"
					prop="remark"
				>
					<el-input
						v-model="queryData.remark"
						type="textarea"
						:placeholder="
							$t('funds.capital_adjustment.remark_placeholder')
						"
						clearable
						show-word-limit
						minlength="2"
						maxlength="500"
						v-input="{ name: 'noEmpty' }"
					></el-input>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						@click="handleSubmit"
					>
						{{ $t('common.submit') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 批量导入二级框 -->
		<UploadFiles
			:visibleUpload.sync="visibleUpload"
			:file-size="500"
			:noShowBtn="true"
			:params="queryData.merchantId"
			:fileAPI="fileAPI"
			@fileUrl="getFileUrl"
		></UploadFiles>
		<el-dialog
			:close-on-click-modal="false"
			:visible.sync="dialogVisible"
			:destroy-on-close="true"
			:before-close="reset"
			top="40vh"
			width="30%"
		>
			<div style="text-align:center">
				<i
					class="el-icon-success"
					style="font-size: 48px;color: #67C23A;"
				></i>
				<h3>
					{{ $t('funds.capital_adjustment.bouns_dialog_title') }}
				</h3>
				<p style="display:flex;justify-content: center;">
					{{ $t('funds.order_no') }}：
					<Copy :title="eventId" :copy="copy">
						{{ eventId }}
					</Copy>
					&nbsp;
					{{ $t('funds.capital_adjustment.waiting_audit_results') }}
				</p>
				<br />
				<el-button type="primary" size="medium" @click="reset">
					{{ $t('common.back') }}
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import list from '@/mixins/list'
import { mapGetters } from 'vuex'
import { routerNames } from '@/utils/consts'
import { rules } from './components/rules'
export default {
	name: routerNames.bonusDistribution,
	components: { UploadFiles: () => import('@/components/UploadFiles') },
	mixins: [list],
	data() {
		return {
			loading: false,
			queryData: {
				merchantId: '',
				activityId: '',
				activityName: '',
				activityTitle: '',
				operationType: 1,
				location: 1,
				userName: '',
				bounsAmount: undefined,
				notification: 0,
				remark: '',
				fileUrl: ''
			},
			eventId: '',
			currency: '',
			activityTitleList: [],
			visibleUpload: false,
			dialogVisible: false
		}
	},
	computed: {
		rules() {
			return rules(this)
		},
		...mapGetters(['merchantInfo']),
		fileAPI() {
			return 'setMemberBonusAuditCheckSubmitBonusExcel'
		}
	},
	watch: {
		'merchantInfo.id': {
			handler(newVal) {
				if (newVal) {
					this.queryData.merchantId = newVal
				}
			},
			immediate: true
		},
		'queryData.merchantId': {
			handler(newVal) {
				this.queryData.activityTitle = ''
				this.queryData.merchantName = this.merchantFilter(newVal)
				if (newVal) {
					this.getMemberActivityTitle(newVal)
				} else {
					this.activityTitleList = []
				}
			},
			immediate: true
		},
		'queryData.activityTitle': {
			handler(newVal) {
				this.activityTitleList.forEach((ele) => {
					if (ele.activityTitle === newVal) {
						this.queryData.activityId = ele.id
						this.queryData.activityName = ele.activityName
					}
				})
			}
		},
		'queryData.operationType': {
			handler(newVal) {
				if (newVal === 1) {
					this.queryData.fileUrl = ''
				} else {
					this.queryData.userName = ''
					this.queryData.bounsAmount = undefined
				}
				this.$refs.formRef.clearValidate()
			}
		},
		'queryData.location': {
			handler(newVal) {
				this.queryData.notification = newVal - 1
			}
		},
		'queryData.fileUrl': {
			handler(newVal) {
				this.$refs.formRef.validateField('fileUrl')
			}
		}
	},
	mounted() {},
	methods: {
		// 获得文件地址
		getFileUrl(fileUrl) {
			this.queryData.fileUrl = fileUrl
		},
		handleOperation(val) {
			this.queryData.operationType = val
		},
		searchUserName(val) {
			this.$refs.formRef.validateField(['userName'], (val) => {
				if (!val) {
					const params = {
						merchantId: this.queryData.merchantId,
						userName: this.queryData.userName,
						walletType: '1'
					}
					this.$api.getMemberBalance(params).then((res) => {
						if (res.data) {
							const { userId, currency } = res?.data || {}
							this.currency = currency
							this.queryData.userId = userId
						} else {
							this.$message.error(res.msg)
						}
					})
				}
			})
		},
		handleSubmit() {
			// this.dialogVisible = true
			const formData = new FormData()
			formData.append('merchantId', this.queryData.merchantId)
			formData.append('merchantName', this.queryData.merchantName)
			formData.append('activityTitle', this.queryData.activityTitle)
			formData.append('activityId', this.queryData.activityId)
			formData.append('activityName', this.queryData.activityName)
			formData.append('operationType', this.queryData.operationType)
			formData.append('location', Number(this.queryData.location))
			formData.append('billMultiple', this.queryData.billMultiple)
			formData.append('notification', this.queryData.notification)
			formData.append('remark', this.queryData.remark)
			formData.append('operator', window.localStorage.getItem('username'))

			if (this.queryData.operationType === 1) {
				formData.append('userName', this.queryData.userName)
				formData.append('bounsAmount', this.queryData.bounsAmount)
			} else {
				formData.append('file', this.queryData.fileUrl)
				formData.append('bounsAmount', 0)
			}
			this.$refs.formRef.validate((valid) => {
				if (valid) {
					this.loading = true
					this.$api
						.setMemberBonusAuditSubmitBonus(formData)
						.then((res) => {
							this.eventId = res?.data[0] || ''
							this.dialogVisible = true
							this.loading = false
						})
						.catch(() => {
							this.loading = false
						})
				}
			})
		},
		reset() {
			this.dialogVisible = false
			this.$refs.formRef.resetFields()
			this.$nextTick(() => {
				this.$refs.formRef.clearValidate()
			})
		},
		getMemberActivityTitle(val) {
			this.activityTitleList = []
			const formData = new FormData()
			formData.append('merchantId', val)
			this.$api
				.getMemberBonusAuditActivityConfigTitle(formData)
				.then((res) => {
					this.activityTitleList = res.data
				})
		},
		handleExport() {
			if (!this.queryData.merchantId) {
				this.$message.error(
					this.$t('funds.capital_adjustment.form_rules_tip2')
				)
			} else {
				this.visibleUpload = true
			}
		},
		downloadExcel() {
			const loading = this.$loading({
				lock: true,
				text: '',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			this.$api
				.getMemberBonusAuditDownload()
				.then((res) => {
					const { data, status } = res
					if (res && status === 200) {
						loading.close()
						const { type } = data
						if (type.includes('application/json')) {
							const reader = new FileReader()
							reader.onload = (evt) => {
								if (evt.target.readyState === 2) {
									const {
										target: { result }
									} = evt
									const ret = JSON.parse(result)
									if (ret.code !== 200) {
										this.$message({
											type: 'error',
											message: ret.msg,
											duration: 1500
										})
									}
								}
							}
							reader.readAsText(data)
						} else {
							const result = res.data
							const disposition =
								res.headers['content-disposition']
							const fileNames =
								disposition && disposition.split("''")
							let fileName = fileNames[1]
							fileName = decodeURIComponent(fileName)
							const blob = new Blob([result], {
								type: 'application/octet-stream'
							})
							if ('download' in document.createElement('a')) {
								const downloadLink = document.createElement('a')
								downloadLink.download = fileName || ''
								downloadLink.style.display = 'none'
								downloadLink.href = URL.createObjectURL(blob)
								document.body.appendChild(downloadLink)
								downloadLink.click()
								URL.revokeObjectURL(downloadLink.href)
								document.body.removeChild(downloadLink)
							} else {
								window.navigator.msSaveBlob(blob, fileName)
							}
							this.$message({
								type: 'success',
								message: this.$t('common.download_success'),
								duration: 1500
							})
						}
					}
				})
				.catch(() => {
					this.loading = false
					this.$message({
						type: 'error',
						message: this.$t('common.download_fail'),
						duration: 1500
					})
				})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep.addAgent-content {
	width: 900px;
	margin: 40px auto;
	border: 1px solid #dcdfe6;
	.form-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20px 0;
		margin-bottom: -15px;
		color: #909399;
	}
	.form-box {
		width: 500px;
		margin: 20px auto;
		.el-select {
			width: 400px;
		}
		.el-input-number .el-input__inner {
			text-align: left;
		}
		.number-box {
			width: 66px;
			text-align: center;
			position: absolute;
			right: 1px;
			top: 3px;
			color: #909399;
			background: #f5f7fa;
			height: 34px;
			line-height: 34px;
		}
	}
}

.vi_VN,
.th_TH,
.en_US {
	.addAgent-content .form-box {
		width: 700px;
	}
}
</style>
